<template>
    <div class="book">
        图书名称：<input type="text" v-model="title">
        图书价格：<input type="text" v-model="price">
        <button @click="onSubmit">添加</button>
        <table border="1" width="500px">
            <!-- 头 -->
            <tr>
                <th>图书编号</th>
                <th>图书名称</th>
                <th>图书价格</th>
                <th>操作</th>
            </tr>
            <tr v-for="item,index in list" :key="index">
                <td>{{item.id}}</td>
                 <td>{{item.title}}</td>
                  <td>{{item.price}}</td>
                  <td>
                    <a href="" @click.prevent="edit(item,index)">修改</a> | 
                    <a href="" @click.prevent="del(index)">删除</a>
                  </td>
            </tr>
        </table>
        
    </div>
</template>
<script>
import {ref,toRefs,reactive} from 'vue'
export default {
    setup(props) {
       const price = ref('') 
       const title = ref('')
       const flag = ref(false)//false就是添加 true就是修改
       const editIndex = ref('')
       const data = reactive({
        list:[{title:'vue从入门到精通',price:29,id:1},{title:'vue从入门到入土',price:29,id:2},{title:'vue从入门到放弃',price:29,id:3}]
       })
       const onSubmit = ()=>{
        if(flag.value == false){
             data.list.push({
            id:new Date().getTime(),
            title:title.value,
            price:price.value
          })
            // 添加
        }else{
            // 修改
            data.list[editIndex.value].price = price.value
            data.list[editIndex.value].title = title.value

            flag.value = false




        }
         
          title.value = ''
          price.value = ''


       }
       const del = (index)=>{
        console.log(index);
        data.list.splice(index,1)

       }
       const edit = (item,index)=>{
          price.value = item.price
          title.value = item.title
          flag.value = true
          editIndex.value = index
       }
       return {price,title,...toRefs(data),onSubmit,del,edit}
    }
}
</script>
<style lang="scss" scoped>
table{
    margin: 0 auto;
}
</style>
